package com.paging.service.impl;

import com.paging.mapper.AuthorMapper;
import com.paging.mapper.BookAuthorMapper;
import com.paging.mapper.BookMapper;
import com.paging.pojo.Author;
import com.paging.pojo.Book;
import com.paging.service.BookService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 位置：SSM/com.paging.service.impl
 * 时间：2023-04-24-19:15
 * 作者：Administrator
 **/

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BookMapper bookMapper;

    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    BookAuthorMapper bookAuthorMapper;

    @Override
    public List<Book> queryBookList() {
        return bookMapper.queryBookList();
    }

    @Override
    public int count(String bookName, String bookType) {
        return bookMapper.count(bookName,bookType);
    }

    @Override
    public void addBook(Book book) {
//        生成书籍编号(使用时间戳)
        String bookNumber = System.currentTimeMillis()+"";
        book.setBookNumber(bookNumber);
        String authorName = book.getBookAuthor();

        String authorId = authorMapper.queryAuthorIdByName(authorName);

        bookAuthorMapper.addBookAuthor(bookNumber,authorId);

        authorMapper.updateBookCount(authorName);

        bookMapper.addBook(book);
    }

    @Override
    public void deleteBook(String bookNumber) {
        String authorId = bookAuthorMapper.queryAuthorIdByBookNumber(bookNumber);
        String authorName = authorMapper.queryAuthorNameById(authorId);
        authorMapper.updateBookCount2(authorName);
        bookAuthorMapper.deleteBookAuthorByBookNumber(bookNumber);
        bookMapper.deleteBook(bookNumber);
    }

    @Override
    public void updateBook(Book book) {
        bookMapper.updateBook(book);
    }

    @Override
    public void deleteBookByIds(String idList) {
        idList = idList.substring(0,idList.length()-1);
        bookMapper.deleteBookByIds(idList);
    }

    @Override
    public List<Book> queryBookListByPage(Integer start,Integer pageSize, String bookName, String bookType) {
        if(start != null){
            if(start > 1){
                start = (start - 1) * pageSize;
            }else{
                start = 0;
            }
        }
        return bookMapper.queryBookListByPage(start,pageSize,bookName,bookType);
    }

}
